//
//  BGView.m
//  GestureDemo
//
//  Created by ZJ on 2018/8/6.
//  Copyright © 2018年 iCatch Technology Inc. All rights reserved.
//

#import "BGView.h"
#import "ZJView.h"

@interface BGView ()

@property (weak, nonatomic) IBOutlet ZJView *greenView;
@property (nonatomic, strong) NSArray<UIImage *> *images;


@end

@implementation BGView

#pragma mark - 多点触摸
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self == [super initWithCoder:aDecoder]) {
        self.backgroundColor = [UIColor blackColor];
        self.multipleTouchEnabled = YES; // 必须使能才能实现多点触摸
    }
    
    return self;
}

- (NSArray<UIImage *> *)images {
    if (_images == nil) {
        _images = @[
                    [UIImage imageNamed:@"spark_blue"],
                    [UIImage imageNamed:@"spark_cyan"],
                    [UIImage imageNamed:@"spark_green"],
                    [UIImage imageNamed:@"spark_magenta"],
                    [UIImage imageNamed:@"spark_red"],
                    [UIImage imageNamed:@"spark_yellow"]
                    ];
    }
    
    return _images;
}

// 手指触摸这个 view 的时候调用
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    self.greenView.hidden = YES;

    [self addSpark:touches];
}

// 手指在这个 view 移动的时候调用
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self addSpark:touches];
}

// 根据手指的位置 添加小星星
- (void)addSpark:(NSSet<UITouch *> *)touches {
    int i = 0;
    
    for (UITouch *t in touches) {
        // 获取手指的位置
        CGPoint p = [t locationInView:t.view];
        
        // 创建 imageView
        UIImageView *imageView = [[UIImageView alloc] initWithImage:self.images[i]];
        
        // 设置 imageView 的中心为手指的位置
        imageView.center = p;
        
        // 把 imageView 加到黑色 view 上
        [self addSubview:imageView];
        
        // 动画
        [UIView animateWithDuration:2 animations:^{
            imageView.alpha = 0;
        } completion:^(BOOL finished) {
            [imageView removeFromSuperview]; // 移除控件
        }];
        
        i++;
    }
}

#pragma mark - 单点触摸案例
/*
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 获取触摸对象
    UITouch *t = touches.anyObject;
    
    // 获取当前点的位置
    CGPoint p = [t locationInView:self];
    
    // 获取上一个点的位置
    CGPoint lastP = [t previousLocationInView:self];
    
    // 计算偏移量
    CGFloat offsetX = p.x - lastP.x;
    CGFloat offsetY = p.y - lastP.y;
    
    // 让绿色 View 的中心 在自身的基础上加上偏移量
    self.greenView.center = CGPointMake(self.greenView.center.x + offsetX, self.greenView.center.y + offsetY);
}
 */

@end
